package com.itboye.jinpuyiyuan.activity.message;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.mobileim.IYWLoginService;
import com.alibaba.mobileim.YWAPI;
import com.alibaba.mobileim.YWIMCore;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.contact.IYWContact;
import com.alibaba.mobileim.contact.YWContactFactory;
import com.alibaba.mobileim.conversation.IYWConversationService;
import com.alibaba.mobileim.conversation.YWConversation;
import com.alibaba.mobileim.conversation.YWConversationCreater;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.adapter.MainAdapter;
import com.itboye.jinpuyiyuan.adapter.NoticeListAdapter;
import com.itboye.jinpuyiyuan.base.BaseFragment;
import com.itboye.jinpuyiyuan.bean.NoticeBean;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.IMKit.LoginSampleHelper;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 通知
 */
public class ServerFragment extends BaseFragment implements Observer, SwipeItemClickListener {
    private SmartRefreshLayout refresh;
    protected SwipeMenuRecyclerView recycler_view;
    protected MainAdapter mAdapter;
    private int pageNo = 1;
    private List<NoticeBean> list;

    private BranchAddressPresenter presenter;
    private String uid;
    String msg_type="00P006002"; //类型  通知00P006002 公告 00P006001
    @Override
    public int initView() {
        return R.layout.message_fragment_good;
    }

    @Override
    public void onMyActivityCreated() {
        presenter=new BranchAddressPresenter(this);
        uid= (String) SPUtils.get(getActivity().getApplication(),null, Const.UID,"");
        list=new ArrayList<>();
        presenter.queryMessage(uid,msg_type,pageNo,10);

        refresh.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）

        mAdapter = new MainAdapter(getActivity());
        recycler_view.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged(list);

        recycler_view.setSwipeItemClickListener(this);//点击事件
        recycler_view.setSwipeMenuCreator(swipeMenuCreator);//菜单创建
        recycler_view.setSwipeMenuItemClickListener(mMenuItemClickListener);//RecyclerView的Item的Menu点击监听

        recycler_view.setLayoutManager(new LinearLayoutManager(getActivity()));//设置布局格式
        //设置Item增加、移除动画
        recycler_view.setItemAnimator(new DefaultItemAnimator());
        //添加分割线
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        recycler_view.addItemDecoration(dividerItemDecoration);

//        //触发自动刷新
        refresh.autoRefresh();
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pageNo = 1;
                        presenter.queryMessage(uid,msg_type,pageNo,10);
                    }
                }, 0);
            }
        });

        //进行加载更多的逻辑处理
        refresh.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pageNo++;
                        presenter.queryMessage(uid,msg_type,pageNo,10);
                    }
                }, 0);
            }
        });

        //设置头布局样式,全局有效
//        refresh.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
//            @Override
//            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
//                //全局设置主题颜色
//                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
//                //指定为经典Header，默认是 贝塞尔雷达Header
//                return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);
//            }
//        });
        //设置脚布局样式,全局有效
        refresh.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
        refresh.setRefreshHeader(new MaterialHeader(getActivity()).setShowBezierWave(true));
        //  refresh.setRefreshFooter(new BallPulseFooter(this).setSpinnerStyle(SpinnerStyle.Scale));
        refresh.finishLoadmore();
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.DIMEN_70DP);

            // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
            // 2. 指定具体的高，比如80;
            // 3. WRAP_CONTENT，自身高度，不推荐;
            int height = ViewGroup.LayoutParams.MATCH_PARENT;
            // 添加右侧的，如果不添加，则右侧不会出现菜单。
            {
                SwipeMenuItem addItem = new SwipeMenuItem(getActivity())
                        .setBackground(R.drawable.selector_green_two)
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(addItem); // 添加菜单到右侧。
            }
        }
    };
    boolean delete = false;//用来标记是删除还是确定删除
    int tag=-1;//用来标记是不是还是点击的同一个位置
    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge) {
            int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
            if (tag!=adapterPosition){
                menuBridge.setText("确认删除");
                delete = false;
                tag=adapterPosition;
            }else{
                menuBridge.setText("删除");
                delete = true;
                tag=-1;
            }
            if (delete){//确定删除
                menuBridge.closeMenu();
                Toast.makeText(getActivity(), "确定删除", Toast.LENGTH_SHORT).show();
            }else{//删除
                Toast.makeText(getActivity(), "删除", Toast.LENGTH_SHORT).show();
            }

        }
    };

    @Override
    public void update(Observable o, Object arg) {
        ResultEntity resultEntity = handlerError(arg);
        if (resultEntity!=null){
            if (resultEntity.getEventType()== BranchAddressPresenter.By_Message_query_success){
                list= (List<NoticeBean>) resultEntity.getData();
                Log.d("===listnotice",list.size()+"");

                if (pageNo == 1) {//下拉刷新
                    mAdapter.refresh(list);
                    //结束加载
                    refresh.finishRefresh();
                } else {//上拉加载
                    mAdapter.loadmore(list);
                    //结束加载
                    refresh.finishLoadmore();
                }
            }else if (resultEntity.getEventType()== BranchAddressPresenter.By_Message_query_fail){
//                MAlert.alert("获取通知列表失败");
                refresh.finishLoadmore();
                refresh.finishRefresh();
            }
        }
    }

    @Override
    public void onItemClick(View itemView, int position) {

    }
}
